<?php

namespace App\Console\Commands\Wanggui;

use App\Enums\OpenShop\FeishuMini\ProgrammingEnum;
use App\Enums\OpenShop\FeishuMini\SandTableEnum;
use App\Enums\OpenShop\InvestmentPromotion\SignOrderEnum;
use App\Exceptions\Custom\ResponseHttpException;
use App\Library\Rms\RmsShopApi;
use App\Models\Common\ResourcesModel;
use App\Models\Guanyuan\GuanyuanSyncShopListModel;
use App\Models\OpenShop\InvestmentPromotion\OpenShopSignOrderModel;
use App\Models\OpenShop\SiteLocation\OpenShopSiteLocationExamineLogModel;
use App\Service\Api\WangguiApiService;
use App\Service\OpenShop\FeishuMini\SandTableService;
use App\Service\OpenShop\SiteLocation\GuanyuanDataService;
use App\Service\Wanggui\WangguiDotService;
use Carbon\Carbon;
use GuzzleHttp\Exception\GuzzleException;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Log;

class KfShopInfoCache extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'wanggui:kf-shop-info-cache';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '网规门店信息缓存';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return int
     * @throws GuzzleException
     */
    public function handle()
    {
        Log::info('WangGui-' . '开始网规门店信息缓存');
        ini_set('memory_limit', '1024M');

        $kfShop = [];
        GuanyuanSyncShopListModel::query()
            ->with(['guanyuanSyncShopBusinessRel' => function ($q) {
                $q->orderBy('date', 'desc')->limit(1);
            }])
            ->with(['shopRel'])
            ->chunkById(100, function ($guanyuanSyncShopLists) use (&$kfShop){
                $kfShop = array_merge($kfShop, $guanyuanSyncShopLists->toArray());
            });

        $defaultImage = [];
        collect($kfShop)->chunk(200)->each(function ($guanyuanSyncShopListModel) use (&$defaultImage) {
            $orderNoWithCode = collect($guanyuanSyncShopListModel)->pluck('orderNo', 'code')->toArray();
            $defaultImage    += WangguiDotService::getShopImageByShopCode([], $orderNoWithCode);
        });

        foreach ($kfShop as $k => $shop) {
            $turnover = $shop['guanyuan_sync_shop_business_rel'][0] ?? [];
            //$shopCode = $shop['铺位号'];
            Log::info('WangGui-' . '缓存的铺位号：' . $shop->code);
            $a = microtime(true);
            //获取折线图
            try {
                $shopId         = $shop['shop_rel']['id'] ?? 0;
                $showTimeTab    = 5;
                $showStartAt    = Carbon::now()->subDays(30)->startOfDay()->timestamp;
                $showEndAt      = Carbon::today()->startOfDay()->timestamp;
                $compareTimeTab = 4;
                $compareStartAt = Carbon::now()->subDays(60)->startOfDay()->timestamp;
                $compareEndAt   = Carbon::now()->subDays(30)->startOfDay()->timestamp;
                //获取折线图
                $res = (new RmsShopApi())->indexCharts($shopId, $showTimeTab, $showStartAt, $showEndAt, $compareTimeTab, $compareStartAt, $compareEndAt);
                if ($res['code'] == 1) {
                    $charts = $res['data'];
                } else {
                    $charts = [];
                }
            } catch (\Exception $exception) {
                $charts = [];
            }

            // 添加预测数据折线图
            if (count($charts)) {
                $charts[] = [
                    'text'           => '预测',
                    'statisticsType' => 1,
                    'numType'        => 1,
                    'lists'          => WangguiApiService::getHistoricalPredictionByWgNumber(str_pad($shop->code, 4, "0", STR_PAD_LEFT))
                ];
            }

            //夸父门店
            $wgNumber = 'KFZC' . str_pad($shop->code, 7, '0', STR_PAD_LEFT);
            $cover    = $defaultImage[$shop->code] ?? SandTableEnum::DEFAULT_COVER_IMAGE_BASIC;  //默认封面图
            //获得评估日志
            $log           = OpenShopSiteLocationExamineLogModel::query()
                ->where('orderNo', $wgNumber)
                ->where('source', OpenShopSiteLocationExamineLogModel::SOURCE_OTHER_WG_AUDIT)
                ->orderByDesc('updatedAt')
                ->first();
            $status        = ProgrammingEnum::STATUS_SCORE_MAPPING[(string)optional($log)->openPotential] ?? '待评估';
            $openPotential = (string)optional($log)->openPotential;

            $data = [
                'cover'         => $cover,
                'fileList'      => [['url' => $cover, 'type' => 'image']],
                'name'          => $shop->name,
                'openPotential' => $openPotential,
                'label'         => [
                    $shop->status,
                    $shop->siteLocationType,
                    $shop->storeType,
                    $shop->cashierSystem,
                ],
                'takeawayScore' => '外卖评分: 美团' . ($turnover['mtRating'] ?: '-') . ' | 饿了么' . ($turnover['elmRating'] ?: '-'),
                'special'       => [
                    [
                        'name'  => '开业日期',
                        'value' => $turnover['openBusinessDate'] ?: '-',
                    ],
                    [
                        'name'  => '已开业',
                        'value' => $turnover['openingDurationMonth'] ? floor($turnover['openingDurationMonth']) . '个月' : '-',
                    ]
                ],
                'grade'         => $shop->shopGrade,
                'lng'           => $shop->lng,
                'lat'           => $shop->lat,
                'province'      => $shop->province,
                'city'          => $shop->city,
                'district'      => $shop->district,
                'address'       => $shop->address,
                'status'        => $status,
                'type'          => 'kfShop',
                'key'           => ProgrammingEnum::KF_SHOP_SAND_TABLE_KEY_MAPPING[ProgrammingEnum::KF_SHOP_STATUS_REVERSE_MAPPING[$shop['状态']] ?? 0] ?? 'kfShop',
                'shopInfo'      => [
                    [
                        'name'  => '门店面积',
                        'value' => $turnover['area'] ? ($turnover['area'] . '㎡') : '-',
                    ], [
                        'name'  => '员工人数',
                        'value' => $turnover['employeesNum'] ?: '-',
                    ], [
                        'name'  => '房租成本',
                        'value' => $turnover['rent'] ? ('¥' . $turnover['rent']) : '-',
                    ], [
                        'name'  => '人力成本',
                        'value' => $turnover['artificial'] ? ('¥' . $turnover['artificial']) : '-',
                    ]
                ],
                'phone'         => [],
                'charts'        => $charts,
            ];
            Cache::put('openShop:sandTable:kfShop:Cache:code:' . $shop->code, $data, 86400);
            $this->info($shop->name . '缓存完成--' . round($k / 2409, 4) * 100 . '%--' . $wgNumber . 'time:' . (microtime(true) - $a));
        }
        Log::info('WangGui-' . '网规门店信息缓存完成');
    }
}
